package com.lzh.hosp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.hosp.model.OrderInfo;
import com.lzh.hosp.model.Patient;
import com.lzh.hosp.model.ResponseResult;
import com.lzh.hosp.model.Schedule;
import com.lzh.hosp.model.vo.OrderInfoQueryVo;
import com.lzh.hosp.service.OrderInfoService;
import com.lzh.hosp.service.PatientService;
import com.lzh.hosp.service.ScheduleService;
import com.lzh.hosp.utils.RedisCache;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/order")
@Tag(name="订单管理")
public class OrderController {
    @Autowired
    private PatientService patientService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RedisCache redisCache;

    //预约挂号
    @PostMapping("add")
    public ResponseResult add(@RequestBody @Validated OrderInfo orderInfo){
        String orderInfoId = orderInfoService.add(orderInfo);
        if (!StringUtils.isEmpty(orderInfoId)){
            return ResponseResult.ok(orderInfoId);
        }else {
            return ResponseResult.fail("预约挂号失败");
        }
    }

    //现场加号
    @PostMapping("registerOnSite")
    public ResponseResult registerOnSite(@RequestBody @Validated OrderInfo orderInfo){
        //判断就诊卡是否存在
        String cardNo = orderInfo.getCardNo();
        QueryWrapper<Patient> patientWrapper = new QueryWrapper<>();
        patientWrapper.eq("card_no",cardNo);
        Patient patient = patientService.getOne(patientWrapper);
        if (StringUtils.isEmpty(patient)){
            return ResponseResult.fail("就诊卡不存在");
        }

        //判断是否重复挂号
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("card_no",orderInfo.getCardNo());
        wrapper.eq("schedule_id",orderInfo.getScheduleId());
        wrapper.and(queryWrapper->{
            queryWrapper.eq("order_status",0).or().eq("order_status",2).or().eq("order_status",4);//未支付或者已支付的不能重复挂号
        });
        OrderInfo info = orderInfoService.getOne(wrapper);
        if (!StringUtils.isEmpty(info)){//说明已重复挂号
            return ResponseResult.fail("重复挂号");
        }

        //设置其他值
        //设置已经支付
        orderInfo.setOrderStatus(2);
        orderInfo.setPayTime(new Date());
        //设置金额
        //查出排班
        Schedule schedule = scheduleService.getById(orderInfo.getScheduleId());
        orderInfo.setAmount(schedule.getAmount());
        //保存
        boolean save = orderInfoService.save(orderInfo);
        return save?ResponseResult.ok():ResponseResult.fail("插入失败");
    }

    @GetMapping("/findById/{id}")
    public ResponseResult findById(@PathVariable String id){
        OrderInfo orderInfo = orderInfoService.findById(id);
        return ResponseResult.ok(orderInfo);
    }

    @PostMapping("/findByObj")
    public ResponseResult findByUserId(@RequestBody OrderInfoQueryVo orderInfoQueryVo){
        List<OrderInfo> list = orderInfoService.getByObj(orderInfoQueryVo);
        return ResponseResult.ok(list);
    }

    @GetMapping("/pay/{orderId}")
    public ResponseResult payOrder(@PathVariable String orderId){
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        orderInfo.setOrderStatus(2);//2是已支付状态
        orderInfo.setPayTime(new Date());
        orderInfoService.updateById(orderInfo);

        //删除redis中对应的键
        redisCache.deleteObject(orderId);
        redisCache.deleteObject(orderId+"orderInfo");
        
        return ResponseResult.ok();
    }

    @GetMapping("cancel/{orderId}/{reason}")
    public ResponseResult cancelOrder(@PathVariable String orderId,@PathVariable String reason){
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        orderInfo.setOrderStatus(3);
        orderInfo.setCancelReason(reason);
        orderInfo.setQuitTime(new Date());
        orderInfoService.updateById(orderInfo);

        //释放排班余量
        Schedule schedule = scheduleService.getById(orderInfo.getScheduleId());
        schedule.setAvailableNumber(schedule.getAvailableNumber()+1);
        scheduleService.updateById(schedule);

        //删除redis中对应的键
        redisCache.deleteObject(orderId);
        redisCache.deleteObject(orderId+"orderInfo");
        return ResponseResult.ok();
    }

    //患者报到
    @GetMapping("patientRegistration/{orderInfoId}")
    public ResponseResult patientRegistration(@PathVariable String orderInfoId){
        boolean flag = orderInfoService.patientRegistration(orderInfoId);
        return ResponseResult.ok(flag);
    }


}
